from .modes.bot_loop import Bot_Loop
from .modes.visits_loop import Visits_Loop
from .modes.channel_loop import Channel_Loop
from .db import LocalDB_JSON

import time
import telethon


async def get_tegmo(client, CONST_NAMED_BOT):
    dlgs = await client.get_dialogs()
    for dlg in dlgs:
        if dlg.title == f"{CONST_NAMED_BOT} Click Bot":
            return dlg
        else:
            pass


def main():
    djb = LocalDB_JSON()
    CONST_NAMED_BOT = djb.get_named_bot()
    clients = []
    i = 0
    while i != -1:
        user = djb.get_user(i)
        if user:
            client = telethon.TelegramClient(
                user["file_session"], user["api_id"], user["api_hash"]
            )
            clients.append(client)
            i += 1
            continue
        else:
            i = -1
    while True:
        for client in clients:
            with client:
                tegmo = client.loop.run_until_complete(
                    get_tegmo(client, CONST_NAMED_BOT)
                )
                visits = Visits_Loop(
                    (client, tegmo),
                    True,
                    (0, 0),
                    CONST_NAMED_BOT,
                )
                client.loop.run_until_complete(visits.exclude_expire_chats())
                total_sorry_round, round_loop = client.loop.run_until_complete(
                    visits.loop()
                )
                bots = Bot_Loop(
                    (client, tegmo),
                    False,
                    (total_sorry_round, round_loop),
                    CONST_NAMED_BOT,
                )
                total_sorry_round, round_loop = client.loop.run_until_complete(
                    bots.loop()
                )
                channels = Channel_Loop(
                    (client, tegmo), False, (total_sorry_round,
                                             round_loop), CONST_NAMED_BOT
                )
                client.loop.run_until_complete(channels.loop())
                print("Next client")
                time.sleep(5)
                continue


if __name__ == "__main__":
    main()
